<script lang="ts" setup>
import {
  ElButton,
  ElInput,
  ElTable,
  ElSwitch,
  ElPagination,
  ElMessageBox,
  ElRow,
  ElCol,
  ElMessage,
} from "element-plus";
import { Plus } from "@vben/icons";
import { onMounted, ref } from "vue";
import addEdit from "./addEdit.vue";
import { list, deleteId, edit } from "#/api/sys/organization";
import { useDebounceFn } from "@vueuse/core";

const organizationName = ref("");
const tableData = ref([]);

const spaceInput = (value: string) => {
  // 过滤空格
  organizationName.value = value.replace(/\s+/g, "");
};

const search = async () => {
  const params = {
    organizationName: organizationName.value,
  };
  const { data } = await list(params);
  if (data.length > 0) {
    tableData.value = data;
  } else {
    tableData.value = [];
  }
};

const debouncedSearch = useDebounceFn(search, 500);

const resetForm = () => {
  organizationName.value = "";
  currentPage.value = 1;
  search();
};
const editItem = (row) => {
  dialogVisible.value.editDialog(row);
};

const delItem = async (row) => {
  try {
    await ElMessageBox.confirm(
      `删除组织会导致该组织下的所有组织、账号、设备、计划都被删除，是否确认?`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              const data = await deleteId(row.id);
              if (data.code == 200) {
                ElMessage.success("删除成功");
                done();
              } else {
                instance.confirmButtonLoading = false;
                ElMessage.error(`删除失败: ${data.msg || "未知错误"}`);
                done();
              }
            } catch (error) {
              instance.confirmButtonLoading = false;
              ElMessage.error(`删除失败: ${error.msg || "未知错误"}`);
            }
          } else {
            done();
          }
        },
      }
    );
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`删除失败: ${error.msg || "未知错误"}`);
      console.error("删除组织失败:", error);
    }
  }
};

const updateStatus = async (row) => {
  // 顶级组织（id为1）不允许修改状态
  if (row.id == 1) {
    // ElMessage({
    //   type: "warning",
    //   message: "顶级组织状态不可修改",
    // });
    return;
  }

  if (row.status == false) {
    try {
      await ElMessageBox.confirm(
        "关闭组织会导致该组织下的所有组织、账号都被禁用，是否确认关闭？",
        "关闭确认",
        {
          type: "warning",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
        }
      );
    } catch (error) {
      row.status = !row.status;
      return;
    }
  }

  const params = {
    id: row.id,
    status: row.status,
  };

  try {
    const data = await edit(params);
    if (data.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      search();
    } else {
      row.status = !row.status;
      ElMessage({
        type: "error",
        message: "修改失败",
      });
    }
  } catch (error) {
    row.status = !row.status;
    ElMessage({
      type: "error",
      message: "修改失败",
    });
    console.error("状态修改失败:", error);
  }
};

const dialogVisible = ref();
const addItem = () => {
  dialogVisible.value.addDialog();
};

onMounted(() => {
  search();
});
</script>

<template>
  <div class="p-2 pageStyle">
    <div class="search">
      <ElRow>
        <ElCol :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="searchCol">
          <!-- <div class="searchForm">
            <div>
              <span class="inputLabel">组织名称：</span>
              <ElInput
                v-model="organizationName"
                style="width: 240px"
                placeholder="请输入组织名称"
                @input="spaceInput"
                clearable
              />
            </div>
            <div class="searchBtn">
              <ElButton
                type="primary"
                style="margin-left: 10px"
                @click="debouncedSearch"
                >查询</ElButton
              >
              <ElButton @click="resetForm()" style="color: #606266"
                >重置</ElButton
              >
            </div>
          </div> -->
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="searchCol">
          <ElButton type="primary" style="float: right" @click="addItem"
            >添加</ElButton
          >
        </ElCol>
      </ElRow>
    </div>
    <div class="tablePage">
      <div style="padding: 0 24px 0 16px">
        <ElTable
          :data="tableData"
          stripe
          default-expand-all
          style="width: 100%"
          row-key="id"
        >
        <!-- class-name="org-name-column" -->
          <ElTable.TableColumn
            prop="organizationName"
            label="组织名称"
            align="left"            
            show-overflow-tooltip
          />
          <ElTable.TableColumn
            prop="chargeName"
            label="负责人"
            align="center"
          />
          <ElTable.TableColumn
            prop="sort"
            label="排序"
            align="center"
            width="80"
          />
          <ElTable.TableColumn
            prop="createTime"
            label="创建时间"
            align="center"
          />
          <ElTable.TableColumn
            prop="status"
            label="状态"
            align="center"
            width="80"
          >
            <template #default="scope">
              <ElSwitch
                :disabled="scope.row.id == 1 || scope.row.disabled == 1"
                v-model="scope.row.status"
                @change="updateStatus(scope.row)"
                style="
                  --el-switch-on-color: #2f69eb;
                  --el-switch-off-color: #c0c4cc;
                "
              />
            </template>
          </ElTable.TableColumn>
          <ElTable.TableColumn fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editItem(scope.row)"
                :disabled="scope.row.id == 1 || scope.row.disabled == 1"
              >
                编辑
              </el-button>
              <!-- :disabled="scope.row.parentId == null" -->
              <el-button
                link
                type="primary"
                size="small"
                @click="delItem(scope.row)"
                :disabled="scope.row.id == 1 || scope.row.disabled == 1"
                >删除</el-button
              >
            </template>
          </ElTable.TableColumn>
        </ElTable>
      </div>
      <!-- <div class="pagination">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 80, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div> -->
    </div>
    <addEdit ref="dialogVisible" @search="search"></addEdit>
  </div>
</template>
<style lang="css" scoped>
.search {
  padding: 16px 24px 20px 16px;
  background: #fff;
}

.tablePage {
  height: calc(100vh - 172px);
  overflow: scroll;
  background: #fff;
}

.el-table--fit {
  height: calc(100vh - 180px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 24px 20px 16px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.el-row {
  display: flex;
  place-content: center center;
}

.searchForm {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}

@media (max-width: 950px) {
  .searchForm {
    flex-direction: column;
    align-items: flex-start;
  }

  .searchBtn {
    margin-top: 10px;
  }
}

/* :deep(.el-table__indent) {
  padding: 0 !important;
}

:deep(.org-name-column) {
  padding-left: 30px !important;
} */
</style>
